/**
 * 
 */
package com.usc.entme;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

/**
 * @author pranav
 *
 */

public class News extends ListActivity {

	private static Context context;
	private List<Message> messages;	
	private String TAG = "Message";
	private static final int REQUEST_CODE = 1234;
	String[] testlistItems = {"exploring", "android", 
			"list", "activities"};
	Boolean bbcNews=true,yahooNews=false;
	Boolean settingsOpened=false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/*
		 * you would have to create a layout file which would go in 
		 /res/layout/news.xml    [ to display a list of news / probably the breaking news]
		 /res/layout/newsItem.xml [ to display the item which is selected by a user ]
		 * 
		 * 
		 * you might have to extend ListActivity instead of using just the general "Activity"
		 * I have extended the Activity just to create the skeleton application
		 * you should be able to set the layout by using

		  setContentView(R.layout.news);

		 */

		context = this;

		/*TextView textview = new TextView(this);
		textview.setText("This is the News tab");
		setContentView(textview);*/

		setContentView(R.layout.testnews);
		getPref();
		populateMessages();

				

	}

	/**
	 * 
	 */
	public void populateMessages() {
		extractNewsMessages();
		settingsOpened=false;
		//List<String> msg1 = new ArrayList<String>(messages.size());
		List<ListItem> msgList = new ArrayList<ListItem>(messages.size());
		
		for(Message msg1 : messages)
		{
			try {
			ListItem temp = new ListItem();
			temp.title= msg1.getTitle();
			temp.webViewLink= msg1.getLink();
			//Log.e(TAG,msg1.getImg());
			if(msg1.getImg()!=null)
			{
			URL imgtemp;
			URL	webURL = msg1.getLink();
				imgtemp = new URL(msg1.getImg());
			
			HttpURLConnection conn = null;
			
				conn = (HttpURLConnection)imgtemp.openConnection();
				//conn = (HttpURLConnection)webURL.openConnection();
			 conn.setDoInput(true);
			
				conn.connect();
			
			 int length = conn.getContentLength();
			 int[] bitmapData =new int[length];
			 byte[] bitmapData2 =new byte[length];
			 InputStream is = null;
			
				is = conn.getInputStream();
			

			 temp.imgBitMap = BitmapFactory.decodeStream(is);
			}
			 //byte[] theByteArray = temp.title.getBytes("UTF-16LE");
			 //temp.imgBitMap = BitmapFactory.decodeByteArray(theByteArray, 0,theByteArray.length);
			// temp.imgBitMap=BitmapFactory.decodeByteArray(temp.title.getBytes(),0,temp.title.getBytes().length);
					
			 msgList.add(temp);
			} catch (Exception e) {
				//What the hell was this .. ? NEVER EVER EAT EXCEPTION LIKE THIS ..
				e.printStackTrace();
			}
		}
		
		 
		
		//setListAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1,msg1));
		setListAdapter(new ListItemArrayAdapter(this,android.R.layout.simple_list_item_1, msgList));
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		String url = messages.get(position).getLink().toString();
		//Log.e(TAG, "the msg " + msg);
		
			Intent i = new Intent(News.this,Url.class );
			Bundle b = new Bundle();
	        b.putString("passed", url);
	        i.putExtras(b);
	        startActivity(i);	
		
	}

	/**
	 * This method is intended to extract the information from the RSS feed
	 * Method would populate the Message object with the data extracted from the feed
	 * 
	 * (i.e. Title ; news ; description ; publication date )
	 * 
	  // TODO - Rectify the comments here once we finalize the code for "Message" object
	 * 
	 */

	private void extractNewsMessages() {

		URL url,url1;
		
		try {
//			url = new URL("http://www.androidster.com/android_news.rss");
			url = new URL("http://feeds.bbci.co.uk/news/mobile/technology/rss.xml?edition=uk");
			url1 = new URL("http://news.yahoo.com/rss/world");
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			
			RssHandler handler = new RssHandler();
			if(bbcNews)
			{
				parser.parse(url.openConnection().getInputStream(), handler);
			}
			
			if(yahooNews)
			{
				parser.parse(url1.openConnection().getInputStream(), handler);
			}
			messages=handler.getMessages();
		}

		catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			e.printStackTrace();
		}
	}

	/**
	 * @return the context
	 */
	public static Context getContext() {
		return context;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.d("Pref","In onResume");
		 getPref();
		 if(settingsOpened)
		 {
		 populateMessages();
		 }
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		
		super.onStart();
		
		 
	}

	/**
	 * 
	 */
	public void getPref() {
		SharedPreferences prefs = PreferenceManager
        .getDefaultSharedPreferences(getBaseContext());
		 
		 bbcNews = prefs.getBoolean("bbcNewsPref", false);
		 
		 yahooNews = prefs.getBoolean("yahooNewsPref", true);
	}

	private void startVoiceRecognitionActivity()
	{
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo...");
		startActivityForResult(intent, REQUEST_CODE);
	}

	/**
	 * Handle the results from the voice recognition activity.
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
		{
			// Populate the wordsList with the String values the recognition engine thought it heard
			ArrayList<String> matches = data.getStringArrayListExtra(
					RecognizerIntent.EXTRA_RESULTS);
			//      wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
			//            matches));

			if(matches.isEmpty())
			{
				Toast.makeText(context, "No Match found", 2);
			}
			else
			{
				Boolean flag = false;
				for(int i=0;i<matches.size();i++)
				{
					if(matches.get(i).equalsIgnoreCase("news"))
					{
							Log.d(TAG, "News detected int Vocie Recognition");
							Intent intent = new Intent(context,News3DActivity.class);
							startActivity(intent);
							flag =true;
							break;
					}
					if(matches.get(i).equalsIgnoreCase("movies"))
					{
						Intent intent = new Intent(context,Movie3DActivity.class);
						startActivity(intent);
						flag =true;
						break;
					}
					if(matches.get(i).equalsIgnoreCase("sports"))
					{
						Intent intent = new Intent(context,Sports3DActivity.class);
						startActivity(intent);
						flag =true;
						break;
					}
					

				}
				if(!flag)
				{
					
					Toast.makeText(context, "No Match found. Try Again!!", Toast.LENGTH_LONG);
					Log.d(TAG, "No match found");
				}

			}

		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		Intent intentActivity;
		// Handle item selection
		switch (item.getItemId()) {
		
		case R.id.threeD:
			if(getLocalClassName().contains("3D")){
				if(getLocalClassName().contains("News")){
				intentActivity = new Intent(getBaseContext(),EntmeActivity.class);
				intentActivity.putExtra("tabHostIndex", 0);
			    startActivity(intentActivity);
				} else if(getLocalClassName().contains("Movies")){
					intentActivity = new Intent(getBaseContext(),EntmeActivity.class);		
					intentActivity.putExtra("tabHostIndex", 1);
					startActivity(intentActivity);
				} else if(getLocalClassName().contains("Sports")){
					intentActivity = new Intent(getBaseContext(),EntmeActivity.class);		
					intentActivity.putExtra("tabHostIndex", 2);
					startActivity(intentActivity);
				}			    
			}else{
				
				if(getLocalClassName().equalsIgnoreCase("News")){
					intentActivity = new Intent(getBaseContext(),News3DActivity.class);			
				    startActivity(intentActivity);
					} else if(getLocalClassName().equalsIgnoreCase("Movies")){
						intentActivity = new Intent(getBaseContext(),Movie3DActivity.class);			
						startActivity(intentActivity);
					} else if(getLocalClassName().equalsIgnoreCase("Sports")){
						intentActivity = new Intent(getBaseContext(),Sports3DActivity.class);			
						startActivity(intentActivity);
					}	
			}
			
			return true;			
		case R.id.Settings:
			settingsOpened=true;
			intentActivity = new Intent(getBaseContext(),Preferences.class);
			startActivity(intentActivity);
			return true;
		case R.id.home:
			intentActivity = new Intent(getBaseContext(),EntmeGridViewActivity.class);
			startActivity(intentActivity);
			return true;
		case R.id.speak:
			startVoiceRecognitionActivity();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

}




